var Player = require('../domain/player')
var redisClient = require('../dao/redis/redisClient')
var utils = require('../util/utils')
var skillAttack = require('../domain/skillAttack')
var Bag = require("../domain/bag")

var playerCon = module.exports

playerCon.addPlayer = function(userid, name, cb) {
    redisClient.exists('u:' + userid + ':pid', function(err, ret) {
        if (err || ret !== 0) {
            cb(2)
            return
        }
        var pid = utils.uuid(8)
        var basicAttri = {
                str: 4,
                con: 4,
                wil: 4,
                dex: 4,
                spi: 4,
                critHurt: 15
            }
            //初始化装备
        var equipments = {
            weanpon: utils.uuNumber(), //武器
            body: utils.uuNumber(), //身体
            waist: utils.uuNumber(), //腰带
        }
        var weanpon = global.equipments.get(220101)
        var body = global.equipments.get(130101)
        var waist = global.equipments.get(160101)
        var p = {
            id: pid,
            userId: userid,
            name: name,
            basicAttri: basicAttri,
            equipments: equipments,
            skills: [0, 0, 0],
            lvlexp: global.lvlexp[1]
        }
        var player = new Player(p)
            //物品详细信息
        var itemInfo = {}
        itemInfo[equipments.weanpon] = weanpon
        itemInfo[equipments.body] = body
        itemInfo[equipments.waist] = waist
        player.itemInfo = itemInfo
            //背包
        var bag = new Bag({})
        player.bag = bag
        player.calcAttri()
        player.savePlayer()
        player.saveBag()
        player.saveItemInfo()
        redisClient.set('u:' + userid + ':pid', pid)
        cb(0, player)
    })
}

playerCon.delPlayer = function(userid, playerid) {
    redisClient.del('u:' + userid + ':pid')
    redisClient.del('p:' + playerid) //角色资料
    redisClient.del('b:' + playerid) //角色背包
    redisClient.del('i:' + playerid) //角色物品信息
    redisClient.del('lf:' + playerid) //战斗资料
    global.playerTree.del(playerid)
}

playerCon.lvlPlayer = function(player) {
    player.lvlup()
    player.calcAttri()
    player.savePlayer()
}

playerCon.lvlPlayerByexp = function(player) {
    if (player.exp < player.lvlexp) {
        return -1
    }
    player.exp = player.exp - player.lvlexp
    player.lvlup()
    player.lvlexp = global.lvlexp[player.lvl]
    player.calcAttri()
    player.savePlayer()
    return 0
}

playerCon.battleOnMap = function(player) {
    var mapId = player.mapId
    var queue = global.monsterMap[mapId]
    var l = Math.floor(Math.random() * queue.length)
    var monster = global.monsters.get(queue[l])
    redisClient.set('u:' + player.userId + ':btime', new Date().getTime())
    var fightRecord = skillAttack.startBattle(player, monster)
    player.savePlayer()
    return fightRecord
}